<?php

namespace App\Http\Controllers;

use App\Http\Resources\SpecialCarCollection;
use App\Http\Resources\SpecialCarResource;
use App\SpecialCar;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class SpecialCarController extends Controller
{
    private static $s = [
        'id',
        'licensePlate',
        'vehicleType',
        'updatedDate',
        'photo',
        'remark'
    ];
    /**
     * Display a listing of the resource.
     *
     * @return SpecialCarCollection
     */
    public function index(Request $request): SpecialCarCollection
    {
        //
        // 获取每页显示的条数
        $perPage = $request->perPage ?? $request->per_page ?? 88;
        return new SpecialCarCollection(SpecialCar::query()->select(self::$s)->paginate($perPage));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return SpecialCar|void
     */
    public function store(Request $request)
    {
        //
        // 验证请求
        $specialCar = new SpecialCar();
        // 获取请求中的数据
        $formData = $request->all(self::$s);
        // 将数据映射到freeCar对象中
        collect($formData)->forget('id')->map(function ($v, $k) use ($specialCar) {
            $specialCar->$k = $v;
        });
        // 保存数据
        $res = $specialCar->save();
        // 返回保存结果
        if ($res) {
            return $specialCar;
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\SpecialCar  $specialCar
     * @return Response
     */
    public function show(SpecialCar $specialCar): Response
    {
        //
        return new SpecialCarResource($specialCar->newQuery()->select(self::$s)->get());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\SpecialCar  $specialCar
     * @return SpecialCar|void
     */
    public function update(Request $request, SpecialCar $specialCar)
    {
        //
        // 获取请求中的数据
        $formData = $request->all(self::$s);
        // 将数据映射到freeCar对象中
        collect($formData)->forget('id')->map(function ($v, $k) use ($specialCar) {
            $specialCar->$k = $v;
        });
        $res = $specialCar->update();
        if ($res) {
            return $specialCar;
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\SpecialCar  $specialCar
     * @return Response
     */
    public function destroy(SpecialCar $specialCar): Response
    {
        //
        try {
            return $specialCar->delete();
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
}
